<template>
  <view class="pay">
    <public-loading></public-loading>
    <z-nav-bar id="nav" bgColor="#ffffff" title="支付"></z-nav-bar>
    <!-- 支付信息 -->
    <view class="payment-info">
      <view class="top-box">
        <text>订单编号</text>
        <text>{{placeOrderInfo.orderNo}}</text>
      </view>
      <view class="middle-box">
        <text>订单金额</text>
        <text class="price">¥{{originalRrice}}</text>
      </view>
      <view class="middle-amount mgt-20">
        <text>¥</text>
        <text class="big-price">{{totalPrice}}</text>
      </view>
      <view class="bottom-text">待付金额</view>
    </view>

    <view class="pls-select">
      请选择支付方式
    </view>
    <view class="pay-method-wrap">
      <view class="pay-method-list">
        <view class="pay-method-item df">
          <view class="pay-method-item_left df">
            <image src="../static/icon/wxpay.png"></image>
            <text class="pay-method-label">微信支付</text>
          </view>
          <view class="pay-method-item_right">
            <image v-if="paymentMethod==='WX_PAY'"   src="@/static/icon/icon_round_active.png"></image>
            <image   v-else   @click="setPayWx('WX_PAY')" src="@/static/icon/icon_round_no.png"></image>
          </view>

        </view>
        <view class="pay-method-item" v-for="(item,index) in teamList" :key="index">
            <view class="pay-method-top">
              <image src="../static/icon/tuanti-jt.png"></image>
              <view class="pay-method-name">团体卡支付   <text class="pay-method-discount">卡折扣率：{{item.cardDiscount}} 折</text></view>
            </view>
          <view class="pay-method-bottom" >
            <view>可支付额度 （<text class="pay-method-bottom_color">{{item.availableAmount}}</text> 元）</view>
              <view class="pay-method-item_right">
                <image v-if="!item.flag"

                       @click="chooseTeamCard(item,index)"   src="@/static/icon/icon_round_no.png"></image>
                <image  v-else     src="@/static/icon/icon_round_active.png"></image>
              </view>
          </view>


        </view>
        <view class="pay-method-item" v-for="(item,index) in vipList" :key="index">
          <view class="pay-method-top">
            <image src="../static/icon/tuanti-jt.png"></image>
            <view class="pay-method-name">会员卡支付   <text class="pay-method-discount" v-if="item.discountRate">卡折扣率：{{item.discountRate}} 折</text></view>
          </view>
          <view class="pay-method-bottom">
            <view>余额 （<text class="pay-method-bottom_color">{{item.totalAmount}}</text> 元）</view>
            <view class="pay-method-item_right">
              <image  v-if="paymentMethod==='MEMBERSHIP_CARD_PAY'"  src="@/static/icon/icon_round_active.png"></image>
              <image v-else @click.stop="handleVipCouponChoose(item,true)" src="@/static/icon/icon_round_no.png"></image>
            </view>
          </view>
          <view class="pay-method-bottom" v-if="item.clothingTicketCount>0">
            <view>衣次卡 （可用次卡 <text class="pay-method-bottom_color">{{item.clothingTicketCount}}</text>次）</view>
            <view class="pay-method-item_right">
              <image v-if="vipChooseInfo.useClothingCard"  @click.stop="handleVipCard(1,false)"   src="@/static/icon/icon_round_active.png"></image>
              <image v-else @click.stop="handleVipCard(1,true)" src="@/static/icon/icon_round_no.png"></image>
            </view>
          </view>
          <view class="pay-method-bottom" v-if="item.shoeTicketCount>0">
            <view>鞋次卡 （鞋次卡<text class="pay-method-bottom_color">{{item.shoeTicketCount}}</text>次 ）</view>
            <view class="pay-method-item_right">
              <image v-if="vipChooseInfo.useShoesCard" @click.stop="handleVipCard(2,false)"   src="@/static/icon/icon_round_active.png"></image>
              <image v-else @click.stop="handleVipCard(2,true)" src="@/static/icon/icon_round_no.png"></image>
            </view>
          </view>


        </view>
      </view>
    </view>

    <view class="bottom-btn-box">
      <main-button @click="payConfirm">确认支付<text class="font-bold">￥{{totalPrice}}</text></main-button>
    </view>
<!--    这个是会员支付弹出-->
    <up-modal :show="state.show" :title="state.title" @confirm="confirm" >
      <view class="slot-content">
        <view>当前订单选择会员卡组合扣费，</view>
        <view>将扣取会员卡余额 <text class="active_blue">{{totalPrice}}</text> 元，</view>
        <view style="width: 100%;text-align: center">衣次卡 <text class="active_blue">{{state.useClothingTicketCount }}</text>次，鞋次卡 <text class="active_blue">{{state.useShoeTicketCount }}</text> 次。</view>
      </view>
    </up-modal>

  </view>
</template>

<script setup>
/**
 * 支付方式 WX_PAY 微信支付/GROUP_CARD_PAY 团体卡支付/MEMBERSHIP_CARD_PAY 会员卡支付/ALI_PAY 支付宝
 */
import { onLoad } from '@dcloudio/uni-app';
import {useCustomStores} from '@/utils/hook'

import {
  ref,
  reactive,
  toRefs
} from 'vue'
import {customerPay, groupGetUserGroupCard,packageQryUserMember} from '@/api/pagesMy/user'
import {customerPayCalculate} from '@/api/cleaningOrder'
import {payCreateOrder} from '../../api/pagesShop/pay'
import {setPlay,expandItems} from '../../utils/common'
import {customerAnalysisMembershipCardPay} from '../../api/pagesMy/user'
const paymentMethod  = ref('WX_PAY') //默认为微信支付
const orderType = ref('shopOrder') //订单类型 是否是店铺下单或者为会员充值
const totalPrice =  ref(0)
const originalRrice = ref(0) //最开始的价格
const {ShopStore,userStore} = useCustomStores()
const {userInfo} = userStore
const {placeOrderInfo} = ShopStore
console.log('placeOrderInfo',placeOrderInfo)
const state =  reactive({
     title:"会员支付",
     show:false,
     content:'',
     teamList:[],
     vipList:[],
     useClothingTicketCount:0,
     useShoeTicketCount:0,
     vipChooseInfo:{
       useClothingCard:false,// 衣服卡
       useShoesCard:false ,//鞋子卡
       id:''
      }

})
const payList = reactive([
  {
    name: '微信支付',
    value: 'WX_PAY',
    checked: true,
  },
  {
    name: '会员卡支付',
    value: 'MEMBERSHIP_CARD_PAY',
    checked: false,
  },
  {
    name: '团体卡支付',
    value: 'GROUP_CARD_PAY',
    checked: false,
  }
 ])
const setPayWx =(value)=>{
  console.log('value',value)
  paymentMethod.value = value
  state.teamList = state.teamList.map((item,s)=>{
    item.flag = false
    return item
  })
  totalPrice.value = originalRrice.value
  state.vipChooseInfo ={
    useClothingCard:false,// 衣服卡
    useShoesCard:false ,//鞋子卡
    id:''
  }
}
//更新团体卡
function chooseTeamCard(item,index){
  state.teamList[index].flag = !state.teamList[index].flag
  state.teamList = state.teamList.map((item,s)=>{
    if(s==!index){
      item.flag = false
    }
    return item
  })
  let list = state.teamList.filter(item=>item.flag)
  //那么支付变为团体卡支付
  if(list.length>0){
    paymentMethod.value = 'GROUP_CARD_PAY'


    handleMoneyPay(list[0].id)
    //我这地方清空会员的一些信息
    state.vipChooseInfo ={
      useClothingCard:false,// 衣服卡
      useShoesCard:false ,//鞋子卡
        id:''
    }
    // console.log('list',list)
  }
}
/****设置选择会员卡,主的***/
function handleVipCouponChoose(item,flag){
  paymentMethod.value = 'MEMBERSHIP_CARD_PAY'
  state.teamList = state.teamList.map((item,s)=>{
    item.flag = false
    return item
  })
  vipChooseInfo.value.id = item.id
  if(flag){
    handleVipPayMoney()
  }
}
/*******当面选择会有卡的鞋子或者衣服卡的时候************/
function handleVipCard(type,flag){
  if(paymentMethod.value !== 'MEMBERSHIP_CARD_PAY'){
    handleVipCouponChoose(vipList.value[0],false)
  }
  if(type===1){
    vipChooseInfo.value.useClothingCard = flag
  }
  if(type===2){
    vipChooseInfo.value.useShoesCard = flag
  }
  handleVipPayMoney()

}
/********计算价格会员支付的时候 *************/
function handleVipPayMoney(){
  customerAnalysisMembershipCardPay({
    ...vipChooseInfo.value,
    totalAmount:originalRrice.value,
    useBalance:true,
    orderActionItemDtoList:expandItems(placeOrderInfo.categories.map(item=>{
      return {
        id:item.id,
        clothingBigType:item.clothingBigType,
        clothingType:item.clothingTypeName ||'',
        clothingTypeImages:item.clothingPicture ||'',
        "washType": "STORE_WASH",
        price:item.price,
        count:item.quantity || 1,
        washingMethod:item.washingMethod,
        isClothingUsed: item.isClothingUsed,
        isShoesUsed: item.isShoesUsed,
        oneClothingUsedNum: item.oneClothingUsedNum,
        oneShoesUsedNum: item.oneShoesUsedNum
      }
    }))

  }).then(res=>{
    totalPrice.value = res.actualAmount
    state.useClothingTicketCount = res.useClothingTicketCount
    state.useShoeTicketCount = res.useShoeTicketCount
  })
}
/********关闭会员弹出 *************/
function confirm(){
  state.show = false
  uni.reLaunch({
    url: '/pagesMy/user/paySuccess?totalAmount='+totalPrice.value+'&orderNo='+placeOrderInfo.orderNo
  })
}
//计算选择支付的价格
function handleMoneyPay(id){
  customerPayCalculate({
    orderNo: placeOrderInfo.orderNo,
    paymentMethod: paymentMethod.value,
    orderAmount:Number(originalRrice.value),
    id
  }).then(res=>{
    totalPrice.value = res
  })
}
function loadTeamCardList(){
  //获取团体卡列表
  groupGetUserGroupCard({
    storeId:  placeOrderInfo.storeId,
    userId:userInfo.userId
  }).then(res=>{
    //过滤卡
    state.teamList = res.filter(item=>{
      return item.cardStatus==='normal' && item.status ==1
    }).map(item=>{
      return {
        ...item,
        flag:false
      }
    })
  })
}
//查询用户的会员支付
function loadVip(){
  packageQryUserMember({
    storeId:  placeOrderInfo.storeId,
    userId:userInfo.userId
  }).then(res=>{
    if(res){
      state.vipList = [{...res}]
    }

  })
}
function wxPay(){
  payCreateOrder({
    outTradeNo:  placeOrderInfo.orderNo,
    tradeType:'order',
    paymentAmount:totalPrice.value
  }).then(res=> {
    console.log('res', res)
    // return
    setPlay(res,()=>{
      uni.reLaunch({
        url: '/pagesMy/user/paySuccess?totalAmount='+totalPrice.value+'&orderNo='+placeOrderInfo.orderNo
      })
    })
  })

}
//会员的支付确认
function payMember(){
  customerPay({
    paymentMethod: paymentMethod.value,
    orderId:placeOrderInfo.orderNo,
    actualPaymentAmount:totalPrice.value,
    totalAmount:originalRrice.value,
    userId:userInfo.userId,
    useClothingTicketCount:state.useClothingTicketCount || 0 ,
    useShoeTicketCount:state.useShoeTicketCount ||0
  }).then(res=>{
    state.show = true
  })
}
//订单的支付
function payConfirm(){
  if(!paymentMethod.value){
    uni.showToast({
      title: '请选择支付方式',
      icon:'none'
    })
    return false
  }
  if(paymentMethod.value=='WX_PAY'){
    wxPay()
    return

  }
  if(paymentMethod.value=='MEMBERSHIP_CARD_PAY'){
    //会员卡支付
    payMember()
    return
  }
  customerPay({
    paymentMethod: paymentMethod.value,
    orderId:placeOrderInfo.orderNo,
    actualPaymentAmount:totalPrice.value,
    totalAmount:originalRrice.value,
    userId:userInfo.userId
  }).then(res=>{
    uni.reLaunch({
      url: '/pagesMy/user/paySuccess?totalAmount='+totalPrice.value+'&orderNo='+placeOrderInfo.orderNo
    })
  })
}
onLoad((options)=>{
  if(options.type){
    orderType.value = options.type
    //根据类型判断
    loadTeamCardList()
    loadVip()
  }
  if(options.totalPrice){
    totalPrice.value = options.totalPrice
    originalRrice.value = options.totalPrice
  }
})
const {teamList,vipList,vipChooseInfo}=toRefs(state)
</script>

<style lang="scss">
page {
  //background-color: #fff;
}
.payment-info {
  padding: 32rpx;
  background: #fff;
  margin: 24rpx;
  border-radius: 16rpx;

  .top-box {
    display: flex;
    justify-content: space-between;
        font-weight: bold;
        font-size: 32rpx;
    margin-bottom: 24rpx;

    text:first-child {
      font-weight: bold;
    }
  }

  .middle-box {
    display: flex;
    justify-content: space-between;
        font-weight: bold;
        font-size: 32rpx;
    margin-bottom: 32rpx;

    text:first-child {
      font-weight: bold;
    }

    .price {
      color: #FF0000;
      font-weight: bold;
    }
  }

  .middle-amount {
    display: flex;
    align-items: baseline;
    justify-content: center;
    margin-bottom: 8rpx;

    text:first-child {
      font-size: 48rpx;
      color: #FF0000;
    }

    .big-price {
      font-size: 72rpx;
      font-weight: bold;
      color: #FF0000;
    }
  }

  .bottom-text {
    font-size: 28rpx;
    color: #999;
    text-align: center;
  }
}
.bottom-btn-box{
  background-color: transparent;
}
.pls-select{
   color: #000;
   font-weight: bold;
   margin: 0 24rpx 16rpx;
 }
.pay-method-wrap{
  box-sizing: border-box;
  width: 100%;
  padding: 0 16rpx;
}
.pay-method-list{
  box-sizing: border-box;
  width: 100%;
  padding: 0 32rpx;
  border-radius: 16rpx;
  background-color: #ffffff;
  // margin: 0 24rpx;
  .pay-method-item{
    box-sizing: border-box;
    justify-content: space-between;
    padding: 32rpx 0 ;
    .pay-method-top{
      display: flex;
      align-items: center;
      >image{
        width: 52rpx;
        height: 52rpx;
      }
      .pay-method-name{
        margin-left: 32rpx;
        font-weight: bold;
        font-size: 32rpx;
        color: #000000;

        .pay-method-discount{
          font-weight: 400;
          font-size: 28rpx;
          color: #999999;
        }
      }

    }
    .pay-method-bottom{
      margin-top: 20rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: #999999;
      display: flex;
      justify-content: space-between;
      .pay-method-bottom_color{
        color:#ff4d4f ;
      }

    }
    .pay-method-item_left{
      align-items: center;
      >image{
        width: 52rpx;
        height: 52rpx;
      }

      .pay-method-label{
        margin-left: 32rpx;
        font-weight: bold;
        font-size: 32rpx;
        color: #000000;
        flex-direction: column;
      }
    }
    .pay-method-item_right{
      >image{
        width: 42rpx;
        height: 42rpx;
      }
    }

  }
}
.active_blue{
 color:  #2979ff
}
</style>
